/**
 * popen 读写示例
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <unistd.h>

int main(void)
{
    FILE *fp = popen("ls -l", "r");
    if (NULL == fp)
    {
        perror("popen error: ");
        exit(EXIT_FAILURE);
    }

    char buf[1024] = {'\0'};
    while (1)
    {
        if (fgets(buf, 1024, fp) == NULL)
        {
            break;
        }
        printf("%s", buf);
        memset(buf, 0, sizeof(buf));
    }
    printf("\n");
    pclose(fp);

    printf("----------------------------------------------------------------------------\n");
    if ((fp = popen("wc -l", "w")) == NULL)
    {
        perror("popen error: ");
        exit(EXIT_FAILURE);
    }
    fprintf(fp, "hello\nworld\n");

    pclose(fp);

    return 0;
}
